﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Ls.Utils;
using Ls.Web.Admin.Areas.Sys.Models;
using Ls.Web.Framework;
using Ls.Web.Framework.Permissions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Ls.Web.Admin.Areas.Sys.Controllers
{
    [Authorize]
    [Area("sys")]
    public class JobController : BaseController
    {
        BackgroundJobService jobService = new BackgroundJobService();
        JobActionService jobActionService = new JobActionService();
        [Permission("Sys.Job.Index")]
        public IActionResult Index()
        {
            return View();
        }
        [Permission("Sys.Job.Index")]
        public IActionResult IndexAjax()
        {
            string name = CommonHelper.ToString(Request.Form["Name"]); 
            string where = " 1=1 ";
            if (name.IsNotNullOrEmpty())
            {
                where += " and (Name like '%" + name.Safe() + "%' )";
            }
            
            var data = jobService.Page("[Id],[Name],[JobType],[Parameters],[Description],[Status],[RunCount],[NextFireTimeUtc],[FireTimeUtc],[PreviousFireTimeUtc],[JobRunTime],[CreateTime],[CreateBy],[ModifyTime],[ModifyBy]", where, "Id");
            return Json(data);
        }
        [Permission("Sys.Job.Logs")]
        public IActionResult LogAjax()
        {
            Guid id = CommonHelper.ToGuid(Request.Form["id"]);
            var data =  jobService.Page("[Id],[JobId],[JobName],[NextFireTimeUtc],[FireTimeUtc],[PreviousFireTimeUtc],[JobRunTime],[Content],[CreateTime],[Status],[ExceptionMessage]", "j_BackgroundJobLog", "JobId='" + id + "'", "CreateTime desc");
            return Json(data);
        }
        public IActionResult GetJob() {
            Guid id = CommonHelper.ToGuid(Request.Form["id"]);
            var data = jobService.GetJob(id);
            return Json(new { title = "编辑", data = data });
        }
        [Permission("Sys.Job.Delete")]
        public IActionResult Delete()
        {
            Guid id = CommonHelper.ToGuid(Request.Form["id"]);
            var result = jobService.Delete(new { id = id });
            jobService.DeleteBySql(@"delete from j_Trigger where JobId=@JobId ; 
delete from j_BackgroundJobLog where JobId=@JobId;", new { JobId = id });
            jobActionService.AddAction(id, "REMOVE");
            return result > 0 ? GetSuccessResult() : GetErrorResult();
        }
        public IActionResult LogDelete()
        {
            var ids = CommonHelper.ToString(Request.Form["ids"]).Split(",").Select(id => CommonHelper.ToInt64(id)).ToList();
            var result = jobService.DeleteBySql(" delete from j_BackgroundJobLog where id in ("+string.Join(",", ids) +")", new { ids = ids });
            return result > 0 ? GetSuccessResult() : GetErrorResult();
        }
        [Permission("Sys.Job.Edit")]
        public IActionResult EditAjax()
        {

            BackgroundJob job = JsonHelper.ToObject<BackgroundJob>(Request.Form["json"]);
            int result = 0;
            if (job.trigger != null && job.trigger.Count > 0)
            {
                foreach (var t in job.trigger)
                {
                    if (!t.CronExpression.IsCronExpression())
                    {
                        return GetErrorResult("Cron表达式【" + t.CronExpression + "】格式有误"); 
                    }
                }
            }
            if (job.Id == Guid.Empty || job.Id == null)
            {
                job.Id = Guid.NewGuid();
                result = jobService.AddJob(job);
                jobActionService.AddAction(job.Id.Value, "Add");
            }
            else
            {
                result = jobService.UpdateJob(job);
                jobActionService.AddAction(job.Id.Value, "UPDATE");
            }

            if (result > 0)
            { 
                return GetSuccessResult();
            }
            else
            {
                return GetErrorResult();
            }
        }
        [Permission("Sys.Job.Runone")]
        public IActionResult runone()
        {
            Guid id = CommonHelper.ToGuid(Request.Form["id"]);
            jobActionService.AddAction(id, "RunOnce");
            return GetSuccessResult();
        }
    }
}